package com.nerve.android.cloudoffice.app.activity.department;

import java.util.ArrayList;
import java.util.List;

import org.nerve.android.NerveActivityGroup;
import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.ViewOnId;
import org.nerve.android.ui.dialog.ConfirmDialog;
import org.nerve.android.ui.dialog.DialogHelper.ConfirmListener;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.activity.assist.UserSettingActivity;
import com.nerve.android.cloudoffice.app.group.IndexGroupActivity;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.common.Resource;
import com.nerve.android.cloudoffice.domain.Department;
import com.nerve.android.cloudoffice.domain.User;
import com.nerve.android.cloudoffice.service.data.DepartmentData;

/**
 * 
 * @project Cloudoffice DepartmentActivity.java
 * @datetime Aug 12, 2013 1:07:15 PM
 * @description 
 *    
 * @author 集成显卡 IBM 
 *			zxingming@qq.com
 *			zengxm@cn.ibm.com
 *
 * @change log:
 *
 */
@SuppressLint("HandlerLeak")
@Acvitity(layout=R.layout.activity_department)
public class DepartmentActivity extends NavigationActivity implements ConfirmListener{
	
	public static final int DEPARTMENT = -1;
	
	@ViewOnId(id=R.id.departmentList)
	private ListView listView;
	@ViewOnId(id=R.id.message_empty)
	private TextView messageTV;
	
	private DepartmentAdapter adapter;
	
	private int TYPE;
	private int selectIndex;
	
	private static final int DEL_FAIL = 1030;
	private static final int DEL_OK = 1031;
	
	private ConfirmDialog delDepartmentD;
	private ConfirmDialog delUserD;
	
	private List<Department> departmentList = new ArrayList<Department>();
	private List<User> userList = new ArrayList<User>();
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg){
			hideProgressDialog();
			switch(msg.what){
			case WORKER_OK:
				adapter.notifyDataSetChanged();
				break;
			case DEL_FAIL:
			case WORKER_FAIL:
				toast(Const.ERROR);
				break;
				
			case DEL_OK:
				toast("操作成功");
				refreshData();
				break;
			}
		}
	};
	
	@Override
	protected void initUI() {
		super.initUI();
		
		setNavTitle("组织管理");
		
		if(OfficeApplication.USER.getPosition() > User.EMPLOYEE)
			customNavigateRightButton("新增", true);
		
		TYPE = DEPARTMENT;
		
		this.listView.setEmptyView(messageTV);
		adapter = new DepartmentAdapter();
		this.listView.setAdapter(adapter);
		
		this.listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				System.out.println("TYPE= " + TYPE+" , index="+ arg2);
				if(TYPE == DEPARTMENT){
					TYPE = arg2;
					//adapter.notifyDataSetChanged();
					new DataWorker().execute();
					setNavTitle("部门职员");
				}else{
					User u = userList.get(arg2);
					putData(Const.SELECT_USER_ID, u);
					
					Intent intent = new Intent(DepartmentActivity.this, UserSettingActivity.class);
					startActivityForResult(intent, 1);
				}
			}
			
		});
		
		this.listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu arg0, View arg1,
					ContextMenuInfo arg2) {
				arg0.add(0, Const.MENU_DEL, 0, "删除选中");
			}
		});
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int index = ((AdapterContextMenuInfo)item.getMenuInfo()).position;
		
		this.selectIndex = index;
		if(TYPE == DEPARTMENT){
			if(delDepartmentD == null){
				delDepartmentD = new ConfirmDialog(this, 
						"删除部门", 
						"警告：删除部门后，部门中的职员也会被删除，请慎用些操作！ 你确定要删除吗？");
				
				delDepartmentD.setConfirmListener(this);
			}
			
			delDepartmentD.show();
		}else{
			if(delUserD == null){
				delUserD = new ConfirmDialog(this, 
						"删除职员", 
						"确定删除此职员吗？删除后，跟他(她)相关的数据也会失效。");
				
				delUserD.setConfirmListener(this);
			}
			delUserD.show();
		}
		
		return super.onContextItemSelected(item);
	}
	
	@Override
	public void onConfirmClick(int position, Object obj) {
		if(position == ConfirmDialog.OK){
			
			showProgressDialog(null, "正在执行删除操作...");
			new DelWorker().execute(selectIndex);
		}
	}
	
	@Override
	protected void initData() {
		super.initData();
	}
	
	@Override
	protected void onNavigateBackButtonClick() {
		if(TYPE == DEPARTMENT){
			NerveActivityGroup group = getActivityGroup(IndexGroupActivity.class);
			group.changeTab(IndexGroupActivity.HOME);
		}
		else{
			TYPE = DEPARTMENT;
			adapter.notifyDataSetChanged();
			
			setNavTitle("组织管理");
		}
	}
	
	@Override
	protected void onNavigateRightButtonClick() {
		super.onNavigateRightButtonClick();
		NerveActivityGroup group = getActivityGroup(IndexGroupActivity.class);
		
		int step = TYPE==DEPARTMENT ? 1 : 2;
		if(TYPE != DEPARTMENT){
			putData(Const.DEPARTMENT, departmentList.get(TYPE));
		}
		group.next(step);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		refreshData();
	}
	
	private void refreshData(){
		showProgressDialog(null, "正在加载信息，请稍候...");
		new DataWorker().execute();
	}
	
	/**
	 * 
	 * @project Cloudoffice DepartmentActivity.java
	 * @datetime Aug 12, 2013 3:16:27 PM
	 * @description 
	 *    
	 * @author 集成显卡 IBM 
	 *			zxingming@qq.com
	 *			zengxm@cn.ibm.com
	 *
	 * @change log:
	 *
	 */
	private class DepartmentAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			if(TYPE == DEPARTMENT)
				return departmentList.size();
			else{
				return userList.size();
			}
		}

		@Override
		public Object getItem(int arg0) {
			if(TYPE == DEPARTMENT)
				return departmentList.get(arg0);
			else
				return userList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			int layout = TYPE == DEPARTMENT?
					R.layout.activity_department_listitem:R.layout.activity_member_listitem;
			
			arg1 = View.inflate(DepartmentActivity.this, layout, null);
			
			if(TYPE == DEPARTMENT){
				Department d = (Department)getItem(arg0);
				((TextView)arg1.findViewById(R.id.title)).setText(d.getName());
			}else{
				User u = (User)getItem(arg0);
				
				String position = "";
				if(u.getPosition() < Resource.User.POSITION.length && u.getPosition() >= 0){
					position = Resource.User.POSITION[u.getPosition()] ;
				}
				
				String content = u.getSign();
							//"电话:" + u.getCellPhone() + "    地址:"+u.getAddress();
				
				((TextView)arg1.findViewById(R.id.username)).setText(u.getName());
				((TextView)arg1.findViewById(R.id.position)).setText(position);
				((TextView)arg1.findViewById(R.id.content)).setText(content);
				
				((ImageView)arg1.findViewById(R.id.header)).
						setImageResource(DepartmentData.getHeaderResource(u.getSex(), u.getHeader()));
			}
			
			return arg1;
		}
	}
	
	private class DataWorker extends AsyncTask<Void, Void, Integer>{

		@Override
		protected Integer doInBackground(Void... params) {
			if(TYPE == DEPARTMENT){
				departmentList = DepartmentData.getDepartmentList();
			}else{
				Department d = departmentList.get(TYPE);
				
				userList = DepartmentData.getUserList(d.getId());
			}
			return WORKER_OK;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
	}
	
	private class DelWorker extends AsyncTask<Integer, Void, Integer>{

		@Override
		protected Integer doInBackground(Integer... params) {
			Reply re = new Reply();
			
			if(TYPE == DEPARTMENT){
				re = DepartmentData.deleteDepartment(
						departmentList.get(selectIndex).getId()
						);
			}else{
				User u = userList.get(selectIndex);
				re = DepartmentData.deleteUser(u.getDepartment().getId(), u.getId());
			}
			
			if(re.isError()){
				Const.ERROR = re.getMessage().toString();
				return DEL_FAIL;
			}
			
			return DEL_OK;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
	}
}